#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <set>
#include <limits.h>
#include "tree.h"

using namespace std;

void inOrderTraverse(Tree *root, vector<int> &preOrder)
{
    if (!root) return;
    preOrder.push_back(root->data);
    inOrderTraverse(root->left, preOrder);
    inOrderTraverse(root->right, preOrder);
}

Tree *recoverTreeHelper(int lo, int hi, vector<int> &preOrder, int &index)
{
    if (index >= preOrder.size()) return NULL;
    if (preOrder[index] < lo || preOrder[index] > hi) {
        int test = 0;    
	return NULL;
    }
    Tree *head = new Tree(preOrder[index++]);
    head->left = recoverTreeHelper(lo, head->data, preOrder, index);
    head->right = recoverTreeHelper(head->data, hi, preOrder, index);
    return head;
}

Tree *recoverTree(vector<int> &preOrder)
{
   int index = 0;
   return recoverTreeHelper(INT_MIN, INT_MAX, preOrder, index); 
}

int main(int argc, char **argv)
{
    int input[] = {21,7,5,6,3,2,1,4,6,23,43,54,12,54,8,10,11,35,56};
    //int input[] = {7};
    Tree *root = NULL, *root2 = NULL;
    vector<int> preOrder;
    int result;

    for (int i = 0; i < sizeof(input)/sizeof(int); i++) {
        TreeInsert(root, input[i]);
    }
    print_ascii_tree(root);
    inOrderTraverse(root, preOrder);
    Tree *head = recoverTree(preOrder);
    print_ascii_tree(head);
}
